package com.example.xy_assistant;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class TelActivity extends AppCompatActivity {
    List<Map<String, Object>> list;
    private ListView list_tel;
    String number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tel);
        initView();
        SimpleAdapter sda = new SimpleAdapter(this,
                getData(),
                android.R.layout.simple_list_item_2,
                new String[]{"name", "tel"},
                new int[]{android.R.id.text1, android.R.id.text2});

        list_tel.setAdapter(sda);
        list_tel.setOnItemClickListener((parent, view, position, id) -> {
            number = Objects.requireNonNull(list.get(position).get("tel")).toString();
            callPhone();
        });
    }

    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},1);
        }else {
            startActivity(intent);
        }
    }

    private List<Map<String, Object>> getData() {
        String[] deptName = {"院办公室", "互联网工程系", "招生处", "就业处"};
        String[] deptTel = {"073185202048", "073185207112", "073185202868", "073185202779"};
        list = new ArrayList<>();

        for (int i = 0; i < deptName.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", deptName[i]);
            map.put("tel", deptTel[i]);
            list.add(map);
        }
        return list;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED) {
                    callPhone();
                    Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                }
        }
    }

    private void initView() {
        list_tel = (ListView) findViewById(R.id.list_tel);
    }
}